#!/usr/bin/python 
# -*- coding=utf-8 -*-

import tornado.ioloop
import tornado.web
import json
import logging

class DataHandler(tornado.web.RequestHandler):
    def initialize(self, db, idg, conf):
        self.db = db
        self.idg = idg
        self.conf = conf

    def get(self, topic, block, id):
        # validate user
        collection_name = topic + '##' + block
        col = self.db[collection_name]
        #self.write('collection name = %s, size: %d' % (collection_name, col.count()))
        # find pack-size items wihch _id > id
        limit = self.conf.get('broker', 'read-limit')
        result = []
        for data in  col.find({'_id': {"$gt": int(id)}}, limit = int(limit)):
            result.append(dict(data))
        self.write(json.dumps(result))

    def post(self, topic, block, id):
        # validate user
        # check topic, block exists
        collection_name = topic + '##' + block
        col = self.db[collection_name]
        # check block size
        block_size = int(self.conf.get('broker', 'block-size'))
        if col.count() > block_size:
            #data = col.find().sort("_id", -1).limit(1)
            data = col.find_one(sort=[("_id",-1)])
            result = {
                'status': 'BlockFull',
                'last-id': data['_id']
            }
            self.write(json.dumps(result))
            return
        
        # write to db engine
        lastid = 0
        data = self.get_arguments('data')
        for item in data:
            lastid = self.idg.getID()
            col.insert({'_id': lastid, 'data': item})
            logging.debug('insert data: %s' % item)

        self.write('{"status": "OK", "last-id":"%d"}' % lastid)

if __name__ == '__main__':
    app = tornado.web.Application([
       (r'/([0-9a-zA-Z]+)/([a-zA-Z0-9]+)/([0-9]*)', DataHandler),
       ])
    app.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
